package com.sunshine.controller.admin;

import com.sunshine.bean.User;
import com.sunshine.constant.StatusCode;
import com.sunshine.exception.InvalidUserException;
import com.sunshine.exception.PasswordIncorrectException;
import com.sunshine.security.AuthService;
import com.sunshine.security.JwtUserDetailsService;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.common.logging.ESLoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

import static com.sunshine.util.Result.json;


/**
 * Created by along on 4/20/18.
 */
@RestController
@RequestMapping("/api/auth")
public class AuthController {

    private static final Logger LOGGER = ESLoggerFactory.getLogger(AuthController.class);

    @Autowired
    private AuthService authService;

    @Autowired
    private JwtUserDetailsService userDetailsService;

    /**
     * 同一登录接口，成功则返回token
     *
     * @param name
     * @param password
     * @return
     */
    @PostMapping
    public Map<String, Object> login(@RequestParam("username") String name,
                                     @RequestParam("password") String password) {
        User user = userDetailsService.loadNativUserByName(name);

        if (user == null) {
            return json(StatusCode.USER_NOT_FOUND);
        }

        user.setPassword(password);
        try {
            return authService.login(user)
                    .map(jwtUser -> json(StatusCode.SUCCESS, "token", jwtUser.getCurrentToken()))
                    .get();
        } catch (InvalidUserException e) {
            return json(StatusCode.USER_NOT_FOUND);
        } catch (PasswordIncorrectException e) {
            return json(StatusCode.PASSWORD_INCORRECT);
        }

    }

}
